package com.relation.action;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.relation.domain.Recommendation;
import com.relation.domain.Resource;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class CreateRecommendationAction extends ActionBase {

	private static Configuration cfg;
	private String result;
	
	public String execute()
	{
		Recommendation recommendation = new Recommendation();
		Resource backgroundPic = new Resource();
		backgroundPic.setUrl("abc.gif");
		recommendation.setBackgroundPic(backgroundPic);
		try {
			result = applyTemplate(recommendation);
		} catch (IOException e) {
			error(e);
		} catch (TemplateException e) {
			error(e);
		}
		return SUCCESS;
	}
	
	private synchronized static Configuration getTemplateConfiguration()
	{
		if (cfg == null)
		{
			try {
				cfg = createTemplateConfiguration();
			} catch (IOException e) {
				error(e);
			}
		}
		return cfg;
	}
	
	private static Configuration createTemplateConfiguration() throws IOException
	{
		String root = ServletActionContext.getServletContext().getRealPath("/");
		String path = root + "templates/";
		Configuration cfg = new Configuration();
        cfg.setDirectoryForTemplateLoading(new File(path));
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        return cfg;
	}
	
	public String applyTemplate(Recommendation recommendation) throws IOException, TemplateException
	{
		Configuration cfg = getTemplateConfiguration();
		
        Template temp = cfg.getTemplate("recommendation.ftl");

        Map<String, Object> root = new HashMap<String, Object>();
        root.put("rec", recommendation);

        Writer out = new StringWriter();
        temp.process(root, out);
        out.flush();
        return out.toString();
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getResult() {
		return result;
	}
}
